 @include "lib.awk"
 @include "binsort.awk"
 BEGIN { CohensRule=0.3 }

 function binchop(bins0,bins,tiny,     sort,   hi ) {
   hi = binsort(bins0,bins,sort)
   binchop1(1,hi,bins,1, (tiny ? tiny : CohensRule))
 }
 function binchop1(lo,hi,bins,id,tiny,  b,cut) {
   cut = chopHere(lo,hi,bins,tiny) 
   if (cut) {
     id = 1 + binchop1(lo  ,cut,bins,id,tiny)
     id =     binchop1(cut+1,hi,bins,id,tiny)
   } else 
     for(b=lo; b<=hi; b++) 
       bins[b]["chop"] = id
   return id
 }
 function chopHere(lo,hi,bins,tiny,\
                   best,sd0,b,n,n1,n2,sd1,sd2,now,cut) {
   best = sd0 = sds(lo,hi,bins)
   n    = ns(lo,hi,bins)
   for(b=lo; b<hi; b++) {
     n1 +=  bins[b]["n"]
     n2  =  n - n1
     if (n1 < 5) continue
     if (n2 < 5) continue
     sd1 = sds(lo,  b,bins)
     sd2 = sds(b+1,hi,bins)
     now = n1/(n1+n2) * sd1  + n2/(n1+n2) * sd2
     if (now < best) 
       if(tiny < effectSize(means(lo,b,bins),
                            means(b+1,hi,bins),
                            sd0)) {
      
         best   = now
         cut    = b }
   }
   return cut
 }
